package com.whmskj.xjlhsc.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.whmskj.xjlhsc.controller.fo.AOFo;
import com.whmskj.xjlhsc.controller.vo.*;
import com.whmskj.xjlhsc.entity.*;
import com.whmskj.xjlhsc.mapper.*;
import com.whmskj.xjlhsc.schedul.async.mapper.DbStateClassMapper;
import com.whmskj.xjlhsc.schedul.async.po.DbAccount;
import com.whmskj.xjlhsc.schedul.async.po.DbRelations;
import com.whmskj.xjlhsc.service.EnergyService;
import com.whmskj.xjlhsc.service.ShachangdbhouryieldService;
import com.whmskj.xjlhsc.service.ShachangsbhouryieldService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EnergyServiceImpl implements EnergyService {
    private final EnergyMapper energyMapper;

    @Autowired
    private InventoryMonthMapper inventoryMonthMapper;

    @Autowired
    private ShachangsbhouryieldService yieldService;

    @Autowired
    private ShachangdbhouryieldService dbService;

    @Autowired
    private Gy01VarietiesMaintenanceTableMapper gy01VarietiesMaintenanceTableMapper;

    @Autowired
    private CatalogueOfGy02StationsMapper catalogueOfGy02StationsMapper;

    @Autowired
    private Sb02EquipmentCounterAccountMapper sb02EquipmentCounterAccountMapper;

    @Autowired
    private DbStateClassMapper dbStateClassMapper;

    @Autowired
    public EnergyServiceImpl(EnergyMapper energyMapper) {
        this.energyMapper = energyMapper;
    }

    @Override
    public EnergyVO getEnergyData(LocalDate date, String type) {
        try {
            switch (type) {
                case "today":
                    return getTodayEnergyData(date);
                case "month":
                    return getMonthEnergyData(date);
                case "year":
                    return getYearEnergyData(date);
                default:
                    throw new IllegalArgumentException("不支持的查询类型: " + type);
            }
        } catch (Exception e) {
            log.error("查询能耗数据失败", e);
            throw new RuntimeException("查询能耗数据失败: " + e.getMessage());
        }
    }

    @Override
    public EnergyVO getTodayEnergyData(LocalDate date) {
        log.info("查询今日能耗数据，日期: {}", date);

        // 最近7日区间（含今天）
        java.time.LocalDateTime end = date.atTime(23, 59, 59);
        java.time.LocalDateTime start = end.minusDays(6).withHour(0).withMinute(0).withSecond(0);

        // 总能耗
        Double total = energyMapper.getTotalEnergyBetween(start, end);
        double totalEnergy = total == null ? 0.0 : total;

        // 各工序能耗
        List<EnergyTypeRatioVO> typeRatio = energyMapper.getEnergyByProcessBetween(start, end);
        if (typeRatio == null) typeRatio = new ArrayList<>();
        // 计算占比并保留两位小数
        if (totalEnergy > 0) {
            for (EnergyTypeRatioVO vo : typeRatio) {
                double ratio = (vo.getEnergy() / totalEnergy) * 100.0;
                vo.setRatio(new java.math.BigDecimal(ratio).setScale(2, java.math.RoundingMode.HALF_UP).doubleValue());
                vo.setEnergy(BigDecimal.valueOf(vo.getEnergy()).setScale(2, java.math.RoundingMode.HALF_UP).doubleValue());
            }
        } else {
            for (EnergyTypeRatioVO vo : typeRatio) {
                vo.setRatio(0.0);
                vo.setEnergy(BigDecimal.valueOf(vo.getEnergy()).setScale(2, java.math.RoundingMode.HALF_UP).doubleValue());
            }
        }

        // 趋势：最近7日按日
        List<EnergyTrendVO> trendData = energyMapper.getRecentDaysEnergy(start, end);
        trendData = roundTrendData(trendData, 2);

        return new EnergyVO(totalEnergy, "Kwh", typeRatio, trendData);
    }

    @Override
    public EnergyVO getMonthEnergyData(LocalDate date) {
        log.info("查询本月能耗数据，日期: {}", date);

        // 最近6个月（含本月）
        java.time.LocalDate firstDayThisMonth = date.withDayOfMonth(1);
        java.time.LocalDateTime start = firstDayThisMonth.minusMonths(5).atStartOfDay();
        java.time.LocalDateTime end = firstDayThisMonth.plusMonths(1).minusDays(1).atTime(23, 59, 59);

        // 总能耗
        Double total = energyMapper.getTotalEnergyBetween(start, end);
        double totalEnergy = total == null ? 0.0 : total;

        // 工序占比（区间聚合）
        List<EnergyTypeRatioVO> typeRatio = energyMapper.getEnergyByProcessBetween(start, end);
        if (typeRatio == null) typeRatio = new ArrayList<>();
        if (totalEnergy > 0) {
            for (EnergyTypeRatioVO vo : typeRatio) {
                double ratio = (vo.getEnergy() / totalEnergy) * 100.0;
                vo.setRatio(new java.math.BigDecimal(ratio).setScale(2, java.math.RoundingMode.HALF_UP).doubleValue());
                vo.setEnergy(new java.math.BigDecimal(vo.getEnergy()).setScale(2, java.math.RoundingMode.HALF_UP).doubleValue());
            }
        } else {
            for (EnergyTypeRatioVO vo : typeRatio) {
                vo.setRatio(0.0);
                vo.setEnergy(new java.math.BigDecimal(vo.getEnergy()).setScale(2, java.math.RoundingMode.HALF_UP).doubleValue());
            }
        }

        // 趋势：最近6个月按月
        List<EnergyTrendVO> trendData = energyMapper.getRecentMonthsEnergy(start, end);
        trendData = roundTrendData(trendData, 2);

        return new EnergyVO(totalEnergy, "Kwh", typeRatio, trendData);
    }

    @Override
    public EnergyVO getYearEnergyData(LocalDate date) {
        log.info("查询本年能耗数据，日期: {}", date);

        // 最近3年（含本年）
        java.time.LocalDate firstDayThisYear = date.withDayOfYear(1);
        java.time.LocalDateTime start = firstDayThisYear.minusYears(2).atStartOfDay();
        java.time.LocalDateTime end = firstDayThisYear.plusYears(1).minusDays(1).atTime(23, 59, 59);

        // 总能耗
        Double total = energyMapper.getTotalEnergyBetween(start, end);
        double totalEnergy = total == null ? 0.0 : total;

        // 工序占比（区间聚合）
        List<EnergyTypeRatioVO> typeRatio = energyMapper.getEnergyByProcessBetween(start, end);
        if (typeRatio == null) typeRatio = new ArrayList<>();
        if (totalEnergy > 0) {
            for (EnergyTypeRatioVO vo : typeRatio) {
                double ratio = (vo.getEnergy() / totalEnergy) * 100.0;
                vo.setRatio(new BigDecimal(ratio).setScale(2, java.math.RoundingMode.HALF_UP).doubleValue());
                vo.setEnergy(BigDecimal.valueOf(vo.getEnergy()).setScale(2, java.math.RoundingMode.HALF_UP).doubleValue());
            }
        } else {
            for (EnergyTypeRatioVO vo : typeRatio) {
                vo.setRatio(0.0);
                vo.setEnergy(BigDecimal.valueOf(vo.getEnergy()).setScale(2, java.math.RoundingMode.HALF_UP).doubleValue());
            }
        }

        // 趋势：最近3年按年
        List<EnergyTrendVO> trendData = energyMapper.getRecentYearsEnergy(start, end);
        trendData = roundTrendData(trendData, 2);

        return new EnergyVO(totalEnergy, "Kwh", typeRatio, trendData);
    }

    @Override
    public Object nhfx(String month) {
        List<DbAccount> dbAccounts = dbStateClassMapper.selectDbAccount();
        List<String> types = dbAccounts.stream().map(DbAccount::getTypeOfEquipmentBelonging).distinct().toList();
        SummaryVO summary = new SummaryVO();

        LocalDate localDate = LocalDate.now().withDayOfMonth(1);
        if(StringUtils.hasText(month)) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            YearMonth yearMonth1 = YearMonth.parse(month, formatter);
            localDate = yearMonth1.atDay(1);
        }
        LambdaQueryWrapper<InventoryMonth> qe = new LambdaQueryWrapper<>();
        qe.eq(InventoryMonth::getMonth, localDate.toString());
        InventoryMonth inventoryMonth = inventoryMonthMapper.selectOne(qe);
        String start = inventoryMonth.getOtherOrganiser();
        String end = inventoryMonth.getEndDate();

        List<DbRelations> dbRelations = dbStateClassMapper.selectDbRelations();
        get(summary, start, end, new ArrayList<>(), dbRelations);
        List<SummaryVO.MachineAnalysis> machineAnalyses = types.stream().map(type->{
            SummaryVO.MachineAnalysis zj = new SummaryVO.MachineAnalysis(type);
            List<DbAccount> typeDbAccounts = dbAccounts.stream().filter(f -> f.getTypeOfEquipmentBelonging().equals(type)).toList();
            List<Integer> dbIds = typeDbAccounts.stream().map(DbAccount::getDbId).collect(Collectors.toList());
            SummaryVO s = new SummaryVO();
            get(s, start, end, dbIds, dbRelations);
            zj.setDsNh(s.getDsNh());
            zj.setNh(s.getTotalNh());
            zj.setZhdsNh(s.getZhdsNh());
            if (new BigDecimal(zj.getNh()).compareTo(BigDecimal.ZERO) != 0) {
                zj.setDsNhzb(new BigDecimal(zj.getNh()).divide(new BigDecimal(summary.getTotalNh()), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP).doubleValue());
            }
            return zj;
        }).collect(Collectors.toList());
        summary.setMachineAnalyses(machineAnalyses);
        summary.setMonth(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM")));
        return summary;
    }

    private void get(SummaryVO summary,String start,String end,List<Integer> dbIds,List<DbRelations> dbRelations){
        //总能耗
        BigDecimal totalNh = BigDecimal.ZERO;
        LambdaQueryWrapper<Shachangdbhouryield> dbQueryWrapper = new LambdaQueryWrapper<>();
        dbQueryWrapper.in(!dbIds.isEmpty(), Shachangdbhouryield::getDbid, dbIds);
        dbQueryWrapper.between(Shachangdbhouryield::getDay, start, end);
        List<Shachangdbhouryield> nhList = dbService.list(dbQueryWrapper);
        if (!nhList.isEmpty()) {
            double sum = nhList.stream().mapToDouble(Shachangdbhouryield::getEnergy).sum();
            totalNh = new BigDecimal(sum).setScale(2, RoundingMode.HALF_UP);
        }
        summary.setTotalNh(totalNh.toString());
        List<Integer> mesIds = dbRelations.stream().filter(f -> dbIds.contains(f.getDbId())).map(DbRelations::getMesid).collect(Collectors.toList());
        //总产量
        BigDecimal totalOutput = BigDecimal.ZERO;
        LambdaQueryWrapper<Shachangsbhouryield> yieldQueryWrapper = new LambdaQueryWrapper<>();
        yieldQueryWrapper.in(!mesIds.isEmpty(), Shachangsbhouryield::getMesid, mesIds);
        yieldQueryWrapper.between(Shachangsbhouryield::getDay, start, end);
        List<Shachangsbhouryield> yieldList = yieldService.list(yieldQueryWrapper);
        if (!yieldList.isEmpty()) {
            double sum = yieldList.stream().mapToDouble(m-> NumberUtil.parseDouble(m.getActualyieldkg(),0.0)).sum();
            totalOutput = new BigDecimal(sum).divide(BigDecimal.valueOf(1000),4, RoundingMode.HALF_UP);
        }
        summary.setTotalOutput(totalOutput.setScale(2, RoundingMode.HALF_UP).toString());

        Set<Integer> mids = yieldList.stream().map(Shachangsbhouryield::getMesid).collect(Collectors.toSet());
        List<CatalogueOfGy02Stations> catalogueOfGy02Stations = new ArrayList<>();
        List<Sb02EquipmentCounterAccount> sb02EquipmentCounterAccounts = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(mids)) {
            LambdaQueryWrapper<Sb02EquipmentCounterAccount> sb02EquipmentCounterAccountLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sb02EquipmentCounterAccountLambdaQueryWrapper.in(Sb02EquipmentCounterAccount::getId, mids);
            sb02EquipmentCounterAccounts = sb02EquipmentCounterAccountMapper.selectList(sb02EquipmentCounterAccountLambdaQueryWrapper);
            Set<String> stationNumbers = sb02EquipmentCounterAccounts.stream().map(Sb02EquipmentCounterAccount::getPlatform).collect(Collectors.toSet());
            LambdaQueryWrapper<CatalogueOfGy02Stations> catalogueOfGy02StationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            catalogueOfGy02StationsLambdaQueryWrapper.in(CatalogueOfGy02Stations::getStationNumber, stationNumbers);
            catalogueOfGy02Stations = catalogueOfGy02StationsMapper.selectList(catalogueOfGy02StationsLambdaQueryWrapper);
        }
        List<Gy01VarietiesMaintenanceTable> gy01VarietiesMaintenanceTables = gy01VarietiesMaintenanceTableMapper.selectList(null);

        //折合产量
        BigDecimal zhOutput = BigDecimal.ZERO;

        if (totalOutput.compareTo(BigDecimal.ZERO) != 0) {

            for (Shachangsbhouryield proYield : yieldList) {
                Integer mesid = proYield.getMesid();
                String stationNumber = sb02EquipmentCounterAccounts.stream().filter(f -> f.getId().equals(mesid)).findFirst().orElseGet(Sb02EquipmentCounterAccount::new).getPlatform();
                CatalogueOfGy02Stations catalogueOfGy02Station = catalogueOfGy02Stations.stream().filter(f -> f.getStationNumber().equals(stationNumber)).findFirst().orElseGet(CatalogueOfGy02Stations::new);
                Gy01VarietiesMaintenanceTable gy01VarietiesMaintenanceTable = gy01VarietiesMaintenanceTables.stream().filter(f -> f.getNameOfSpecies().equals(catalogueOfGy02Station.getVarieties())).findFirst().orElseGet(Gy01VarietiesMaintenanceTable::new);
                double zh = Optional.ofNullable(gy01VarietiesMaintenanceTable.getDiscountFactor()).orElse(1.0);
                zhOutput = zhOutput.add(new BigDecimal(proYield.getActualyieldkg()).multiply(new BigDecimal(zh)).divide(BigDecimal.valueOf(1000), 2, RoundingMode.HALF_UP));
            }
        }
        summary.setZhOutput(zhOutput.setScale(2, RoundingMode.HALF_UP).toString());

        //吨纱耗能
        BigDecimal dsNh = BigDecimal.ZERO;

        if (totalOutput.compareTo(BigDecimal.ZERO) != 0) {
            dsNh = totalNh.divide(totalOutput, 2, RoundingMode.HALF_UP);
        }

        summary.setDsNh(dsNh.toString());
        //折合吨纱耗能
        BigDecimal zhdsNh = BigDecimal.ZERO;
        if (zhOutput.compareTo(BigDecimal.ZERO) != 0) {
            zhdsNh = totalNh.divide(zhOutput, 2, RoundingMode.HALF_UP);
        }
        summary.setZhdsNh(zhdsNh.toString());
    }


    @Override
    public Object getPz(String process) {
        LambdaQueryWrapper<Gy01VarietiesMaintenanceTable> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(process), Gy01VarietiesMaintenanceTable::getProcess, process);
        return gy01VarietiesMaintenanceTableMapper.selectList(wrapper);
    }

    @Override
    public Object nhfxCp(AOFo fo) {
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        String baseMonth = StringUtils.hasText(fo.getBaseMonth()) ? fo.getBaseMonth() :now.format(formatter);
        DataCpDto resp = new DataCpDto();
        List<String> monthList = fo.getCpMonthList();
        if(monthList.isEmpty()){
            monthList.add(now.minusMonths(1).format(formatter));
        }
        monthList.add(baseMonth);
        monthList = monthList.stream().sorted(Comparator.comparing(s -> s)).toList();
        resp.setBaseMonth(baseMonth);
        resp.setMonthList(monthList);

        String minMonth = monthList.get(0);
        String maxMonth = monthList.get(monthList.size() - 1);

        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String min = YearMonth.parse(minMonth, formatter)
                .atDay(1).format(formatter1);

        String max = YearMonth.parse(maxMonth, formatter)
                .atDay(1).format(formatter1);

        LambdaQueryWrapper<InventoryMonth> qe = new LambdaQueryWrapper<>();
        qe.eq(InventoryMonth::getMonth,min);
        InventoryMonth minInvent = inventoryMonthMapper.selectOne(qe);

        LambdaQueryWrapper<InventoryMonth> qe1 = new LambdaQueryWrapper<>();
        qe1.eq(InventoryMonth::getMonth,max);
        InventoryMonth maxInvent = inventoryMonthMapper.selectOne(qe1);

        String startDate = minInvent.getOtherOrganiser();
        String endDate = maxInvent.getEndDate();

        LambdaQueryWrapper<Shachangsbhouryield> yieldQueryWrapper = new LambdaQueryWrapper<>();
        yieldQueryWrapper.between(Shachangsbhouryield::getDay, startDate, endDate);
        List<Shachangsbhouryield> yieldList = yieldService.list(yieldQueryWrapper);
        LambdaQueryWrapper<Shachangdbhouryield> dbQueryWrapper = new LambdaQueryWrapper<>();
        dbQueryWrapper.between(Shachangdbhouryield::getDay, startDate, endDate);
        List<Shachangdbhouryield> nhList = dbService.list(dbQueryWrapper);
        String baseDateStr = YearMonth.parse(baseMonth, formatter)
                .atDay(1).format(formatter1);
        LambdaQueryWrapper<InventoryMonth> qe2 = new LambdaQueryWrapper<>();
        qe2.eq(InventoryMonth::getMonth,baseDateStr);
        InventoryMonth baseInventMonth = inventoryMonthMapper.selectOne(qe2);
        //设置基准月总产量、总能耗等信息
        List<Shachangsbhouryield> baseYieldList = yieldList.stream().filter(cur -> {
            DateTime dateTime = DateUtil.parseDate(cur.getDay());
            DateTime begin = DateUtil.parseDate(baseInventMonth.getOtherOrganiser());
            DateTime end = DateUtil.parseDate(baseInventMonth.getEndDate());
            return DateUtil.isIn(dateTime, begin, end);
        }).toList();

        //基准月总产量
        BigDecimal zcl = BigDecimal.ZERO;
        if (CollectionUtil.isNotEmpty(baseYieldList)) {
            double sum = baseYieldList.stream().mapToDouble(m->NumberUtil.parseDouble(m.getActualyieldkg(),0.0)).sum();
            zcl = new BigDecimal(sum).divide(BigDecimal.valueOf(1000), 2, RoundingMode.HALF_UP);
        }
        //基准月总能耗
        BigDecimal znh = BigDecimal.ZERO;
        List<Shachangdbhouryield> basePowerList = nhList.stream().filter(cur -> {
            DateTime dateTime = DateUtil.parseDate(cur.getDay());
            DateTime begin = DateUtil.parseDate(baseInventMonth.getOtherOrganiser());
            DateTime end = DateUtil.parseDate(baseInventMonth.getEndDate());
            return DateUtil.isIn(dateTime, begin, end);
        }).toList();

        if (CollectionUtil.isNotEmpty(basePowerList)) {
            double sum = basePowerList.stream().mapToDouble(Shachangdbhouryield::getEnergy).sum();
            znh = new BigDecimal(sum).setScale(2, RoundingMode.HALF_UP);
        }

        BigDecimal dsNh = BigDecimal.ZERO;
        if (zcl.compareTo(BigDecimal.ZERO) != 0) {
            dsNh = znh.divide(zcl, 2, RoundingMode.HALF_UP);
        }
        Set<Integer> mids = baseYieldList.stream().map(Shachangsbhouryield::getMesid).collect(Collectors.toSet());
        List<CatalogueOfGy02Stations> catalogueOfGy02Stations = new ArrayList<>();
        List<Sb02EquipmentCounterAccount> sb02EquipmentCounterAccounts = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(mids)) {
            LambdaQueryWrapper<Sb02EquipmentCounterAccount> sb02EquipmentCounterAccountLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sb02EquipmentCounterAccountLambdaQueryWrapper.in(Sb02EquipmentCounterAccount::getId, mids);
            sb02EquipmentCounterAccounts = sb02EquipmentCounterAccountMapper.selectList(sb02EquipmentCounterAccountLambdaQueryWrapper);
            Set<String> stationNumbers = sb02EquipmentCounterAccounts.stream().map(Sb02EquipmentCounterAccount::getPlatform).collect(Collectors.toSet());
            LambdaQueryWrapper<CatalogueOfGy02Stations> catalogueOfGy02StationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            catalogueOfGy02StationsLambdaQueryWrapper.in(CatalogueOfGy02Stations::getStationNumber, stationNumbers);
            catalogueOfGy02Stations = catalogueOfGy02StationsMapper.selectList(catalogueOfGy02StationsLambdaQueryWrapper);
        }
        LambdaQueryWrapper<Gy01VarietiesMaintenanceTable> gy01VarietiesMaintenanceTableLambdaQueryWrapper = new LambdaQueryWrapper<>();
        gy01VarietiesMaintenanceTableLambdaQueryWrapper.like(StringUtils.hasText(fo.getProcess()), Gy01VarietiesMaintenanceTable::getProcess, fo.getProcess());
        gy01VarietiesMaintenanceTableLambdaQueryWrapper.like(StringUtils.hasText(fo.getVarietyName()), Gy01VarietiesMaintenanceTable::getNameOfSpecies, fo.getVarietyName());
        List<Gy01VarietiesMaintenanceTable> gy01VarietiesMaintenanceTables = gy01VarietiesMaintenanceTableMapper.selectList(gy01VarietiesMaintenanceTableLambdaQueryWrapper);
        List<String> varietyList = gy01VarietiesMaintenanceTables.stream().map(Gy01VarietiesMaintenanceTable::getNameOfSpecies).toList();
        //折合总产量
        BigDecimal zhcl = BigDecimal.ZERO;
        if (CollectionUtil.isNotEmpty(baseYieldList)) {
            for (Shachangsbhouryield proYield : baseYieldList) {
                Integer mesid = proYield.getMesid();
                String stationNumber = sb02EquipmentCounterAccounts.stream().filter(f -> f.getId().equals(mesid)).findFirst().orElseGet(Sb02EquipmentCounterAccount::new).getPlatform();
                CatalogueOfGy02Stations catalogueOfGy02Station = catalogueOfGy02Stations.stream().filter(f -> f.getStationNumber().equals(stationNumber)).findFirst().orElseGet(CatalogueOfGy02Stations::new);
                Gy01VarietiesMaintenanceTable gy01VarietiesMaintenanceTable = gy01VarietiesMaintenanceTables.stream().filter(f -> f.getNameOfSpecies().equals(catalogueOfGy02Station.getVarieties())).findFirst().orElseGet(Gy01VarietiesMaintenanceTable::new);
                double zhl = Optional.ofNullable(gy01VarietiesMaintenanceTable.getDiscountFactor()).orElse(1.0);
                zhcl = zhcl.add(new BigDecimal(proYield.getActualyieldkg()).multiply(new BigDecimal(zhl)));
            }
            zhcl = zhcl.divide(BigDecimal.valueOf(1000),2, RoundingMode.HALF_UP);
        }

        BigDecimal zhdsNh = BigDecimal.ZERO;
        if (zhcl.compareTo(BigDecimal.ZERO) != 0) {
            zhdsNh = znh.divide(zhcl, 2, RoundingMode.HALF_UP);
        }

        resp.setZcl(zcl.toString());
        resp.setZnh(znh.toString());
        resp.setDsNh(dsNh.toString());
        resp.setZhcl(zhcl.toString());
        resp.setZhdsNh(zhdsNh.toString());

        List<DataCpDto.DataRow> rows = new ArrayList<>();
        resp.setRows(rows);
        //查询范围时间类所涉及到的所有品种
        for (Shachangsbhouryield proYield : baseYieldList) {
            Integer mesid = proYield.getMesid();
            String stationNumber = sb02EquipmentCounterAccounts.stream().filter(f -> f.getId().equals(mesid)).findFirst().orElseGet(Sb02EquipmentCounterAccount::new).getPlatform();
            CatalogueOfGy02Stations catalogueOfGy02Station = catalogueOfGy02Stations.stream().filter(f -> f.getStationNumber().equals(stationNumber)).findFirst().orElseGet(CatalogueOfGy02Stations::new);
            proYield.setVarietyName(catalogueOfGy02Station.getVarieties());
        }
        List<Shachangsbhouryield> list = baseYieldList.stream().filter(cur -> StringUtils.hasText(cur.getVarietyName())).toList();
        for (String varietyName : varietyList) {
            DataCpDto.DataRow row = new DataCpDto.DataRow();
            Gy01VarietiesMaintenanceTable one = gy01VarietiesMaintenanceTables.stream().filter(f -> f.getNameOfSpecies().equals(varietyName)).findFirst().orElseGet(Gy01VarietiesMaintenanceTable::new);
            List<Shachangsbhouryield> value = list.stream().filter(f->f.getVarietyName().equals(varietyName)).toList();
            row.setVarietyName(varietyName);
            row.setSz(one.getSaji());
            row.setKts(value.stream().map(Shachangsbhouryield::getMesid).collect(Collectors.toSet()).size()+"");
            double sum = value.stream().mapToDouble(m->NumberUtil.parseDouble(m.getActualyieldkm(),0.0)).sum();
            BigDecimal clm = new BigDecimal(sum).setScale(2, RoundingMode.HALF_UP);
            row.setClm(clm.toString());
            List<MonthKv> clList = Lists.newArrayList();
            List<MonthKv> nhList1 = Lists.newArrayList();
            List<MonthKv> dsNhList = Lists.newArrayList();
            List<MonthKv> zhdsclList = Lists.newArrayList();
            for (String month : monthList) {
                String format = YearMonth.parse(month, formatter)
                        .atDay(1).format(formatter1);
                LambdaQueryWrapper<InventoryMonth> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(InventoryMonth::getMonth,format);
                InventoryMonth inventoryMonth = inventoryMonthMapper.selectOne(queryWrapper);
                List<Shachangsbhouryield> yields = value.stream().filter(cur -> {
                    DateTime dateTime = DateUtil.parseDate(cur.getDay());
                    DateTime begin = DateUtil.parseDate(inventoryMonth.getOtherOrganiser());
                    DateTime end = DateUtil.parseDate(inventoryMonth.getEndDate());
                    return DateUtil.isIn(dateTime, begin, end);
                }).toList();
                Set<Integer> mesIds = yields.stream().map(Shachangsbhouryield::getMesid).collect(Collectors.toSet());
                List<Shachangdbhouryield> statisticsList = nhList.stream().filter(cur -> mesIds.contains(cur.getMesid())).toList();

                //产量
                BigDecimal cl = BigDecimal.ZERO;
                if (CollectionUtil.isNotEmpty(yields)) {
                    for (Shachangsbhouryield proYield : yields) {
                        cl = cl.add(new BigDecimal(proYield.getActualyieldkg()));
                    }
                    cl = cl.divide(BigDecimal.valueOf(1000),2, RoundingMode.HALF_UP);
                }
                clList.add(new MonthKv(month, cl.toString()));
                //能耗
                BigDecimal nh = BigDecimal.ZERO;
                if (CollectionUtil.isNotEmpty(statisticsList)) {
                    for (Shachangdbhouryield statistics : statisticsList) {
                        nh = nh.add(BigDecimal.valueOf(statistics.getEnergy()));
                    }
                    nh = nh.setScale(2, RoundingMode.HALF_UP);
                }
                nhList1.add(new MonthKv(month, nh.toString()));
                //吨纱能耗
                BigDecimal dsNh_m = BigDecimal.ZERO;
                if (cl.compareTo(BigDecimal.ZERO) != 0) {
                    dsNh_m = nh.divide(cl, 2, RoundingMode.HALF_UP);
                }
                dsNhList.add(new MonthKv(month, dsNh_m.toString()));
                //折合产量
                BigDecimal zhdscl = BigDecimal.ZERO;
                if (CollectionUtil.isNotEmpty(yields)) {
                    for (Shachangsbhouryield proYield : yields) {
                        Integer mesid = proYield.getMesid();
                        String stationNumber = sb02EquipmentCounterAccounts.stream().filter(f -> f.getId().equals(mesid)).findFirst().orElseGet(Sb02EquipmentCounterAccount::new).getPlatform();
                        CatalogueOfGy02Stations catalogueOfGy02Station = catalogueOfGy02Stations.stream().filter(f -> f.getStationNumber().equals(stationNumber)).findFirst().orElseGet(CatalogueOfGy02Stations::new);
                        Gy01VarietiesMaintenanceTable gy01VarietiesMaintenanceTable = gy01VarietiesMaintenanceTables.stream().filter(f -> f.getNameOfSpecies().equals(catalogueOfGy02Station.getVarieties())).findFirst().orElseGet(Gy01VarietiesMaintenanceTable::new);
                        double zhl = Optional.ofNullable(gy01VarietiesMaintenanceTable.getDiscountFactor()).orElse(1.0);
                        zhdscl = zhdscl.add(new BigDecimal(proYield.getActualyieldkg()).multiply(new BigDecimal(zhl)));
                    }
                    zhdscl = zhdscl.divide(BigDecimal.valueOf(1000),2, RoundingMode.HALF_UP);
                }
                zhdsclList.add(new MonthKv(month, zhdscl.toString()));
            }
            row.setClList(clList);
            row.setNhList(nhList1);
            row.setDsNhList(dsNhList);
            row.setZhclList(zhdsclList);
            rows.add(row);
        }
        if (StringUtils.hasText(fo.getVarietyName())) {
            resp.setRows(resp.getRows().stream().filter(cur -> cur.getVarietyName().contains(fo.getVarietyName()))
                    .toList());
        }
        return resp;
    }

    private List<EnergyTrendVO> roundTrendData(List<EnergyTrendVO> trendData, int scale) {
        if (trendData == null) {
            return Collections.emptyList();
        }
        for (EnergyTrendVO vo : trendData) {
            double energy = vo.getEnergy();
            double rounded = new java.math.BigDecimal(energy)
                    .setScale(scale, java.math.RoundingMode.HALF_UP)
                    .doubleValue();
            vo.setEnergy(rounded);
        }
        return trendData;
    }
}
